<template>
  <div>
    <el-upload
      action="/proxyApi/thirdparty/oss/upload"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'singleUpload',
  props: {
    value: String
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value) {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      }
      return null;
    },
    fileList() {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }];
    },
    showFileList: {
      get: function () {
        return !!this.value;
      },
      set: function (newValue) {}
    }
  },
  data() {
    return {
      dialogVisible: false,
      //fileList: []
    };
  },
  watch: {
    value(newVal) {
      this.updateFileList();
    }
  },
  methods: {
    updateFileList() {
      this.fileList = this.value ? [{ name: this.imageName, url: this.imageUrl }] : [];
    },
    emitInput(val) {
      this.$emit('input', val);
    },
    handleRemove(file, fileList) {
      this.emitInput('');
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    handleUploadSuccess(response, file) {
      debugger
      console.log("上传成功...", response);
      this.showFileList = true;
      this.fileList.pop();
      this.fileList.push({ name: response.data.name, url: response.data.url });
      this.emitInput(this.fileList[0].url);
      const newUrl = response.data.url;
      this.emitInput(newUrl);
      this.updateFileList(); // 确保 fileList 及时更新
    }
  },
  created() {
    this.updateFileList(); // 初始化时更新 fileList
  }
};
</script>